package ua.kharkov.khpi.tarasenko.bach.web.command.user;

import java.sql.Connection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.order.OrderUserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to show orders' list.
 * 
 * @author oleksandr
 * 
 */
public class ShowOrdersListCommand extends Command {
	private static final Logger log = Logger
			.getLogger(ShowOrdersListCommand.class);
	private static final String ATTRIBUTE_ORDERS_LIST = "ordersList";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		Connection conn = null;
		String forward = Constant.PAGE_ORDERS_LIST;

		// Get user's id from session
		HttpSession session = request.getSession();
		int userId = ((UserBean) session
				.getAttribute(Constant.ATTRIBUTE_USER_BEAN)).getUserId();

		try {

			conn = ConnectionManager.getConnection();
			List<OrderUserDTO> orders = DAOFactory
					.getDAOFactory(DAOFactory.DAO_TYPE.MYSQL)
					.getOrderUserDAO(conn).findOrdersByUserId(userId);

			// Put list of orders into request.
			request.setAttribute(ATTRIBUTE_ORDERS_LIST, orders);
			if (log.isTraceEnabled()) {
				log.trace("Set request attribute " + ATTRIBUTE_ORDERS_LIST
						+ ":\n" + orders);
			}
		} catch (EShopException e) {
			DBUtils.close(conn);
			throw e;
		} finally {
			if (conn != null) {
				DBUtils.close(conn);
			}
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}
}